import React, { useState, useMemo, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  InputNumber, 
  Select, 
  Button, 
  Table, 
  Row, 
  Col, 
  Statistic, 
  Alert, 
  Typography, 
  Space,
  Tag,
  message
} from 'antd';
import { 
  CalculatorOutlined, 
  DownloadOutlined, 
  InfoCircleOutlined,
  TrophyOutlined,
  ArrowLeftOutlined,
  SaveOutlined
} from '@ant-design/icons';
import { StockInvestmentCalculator } from '../../../services/stockInvestmentCalculator';
import {  StockInfo, InvestmentConfig, InvestmentPlan as BaseInvestmentPlan, StrategyType } from '../../../types/investment';
import { SavedStockInvestmentPlan } from './StockInvestmentPlanList';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

interface InvestmentPlan extends BaseInvestmentPlan {
  stockInfo: StockInfo;
}

interface FormValues {
  code: string;
  name: string;
  currentPrice: number;
  maxDrawdown: number;
  totalAmount: number;
  buyTimes: number;
  strategy: StrategyType;
}

interface StockInvestmentPlanFormProps {
  mode: 'create' | 'edit' | 'view';
  initialPlan?: SavedStockInvestmentPlan | null;
  onSave?: (plan: InvestmentPlan) => void;
  onBack: () => void;
}

interface EfficiencyMetrics {
  costAdvantage: number;
}

const StockInvestmentPlanForm: React.FC<StockInvestmentPlanFormProps> = ({
  mode,
  initialPlan,
  onSave,
  onBack
}) => {
  const [form] = Form.useForm<FormValues>();
  const [loading, setLoading] = useState<boolean>(false);
  const [investmentPlan, setInvestmentPlan] = useState<InvestmentPlan | null>(null);
  
  const [stockInfo, setStockInfo] = useState<StockInfo>({
    code: '',
    name: '',
    currentPrice: 0,
    maxDrawdown: -30,
    currency: 'CNY',
    type: 'STOCK'
  });

  const [config, setConfig] = useState<InvestmentConfig>({
    totalAmount: 10000,
    buyTimes: 5,
    strategy: 'pyramid' as StrategyType
  });

  const isReadOnly = mode === 'view';

  useEffect(() => {
    if (initialPlan) {
      // 设置表单初始值
      const formValues: FormValues = {
        code: initialPlan.stockCode,
        name: initialPlan.stockName,
        currentPrice: initialPlan.currentPrice,
        maxDrawdown: initialPlan.maxDrawdown,
        totalAmount: initialPlan.totalAmount,
        buyTimes: initialPlan.buyTimes,
        strategy: initialPlan.strategy as StrategyType
      };
      
      form.setFieldsValue(formValues);
      
      const stockInfoFromPlan: StockInfo = {
        code: initialPlan.stockCode,
        name: initialPlan.stockName,
        currentPrice: initialPlan.currentPrice,
        maxDrawdown: initialPlan.maxDrawdown,
        currency: 'CNY',
        type: initialPlan.stockName.includes('ETF') ? 'ETF':'STOCK',
      };
      
      const configFromPlan: InvestmentConfig = {
        totalAmount: initialPlan.totalAmount,
        buyTimes: initialPlan.buyTimes,
        strategy: initialPlan.strategy as StrategyType,
        riskLevel: 3
      };
      
      setStockInfo(stockInfoFromPlan);
      setConfig(configFromPlan);
      
      // 重新生成投资计划用于显示
      const stockPlan = StockInvestmentCalculator.generateStockInvestmentPlan(stockInfoFromPlan, configFromPlan);
      const plan: InvestmentPlan = {
        config: stockPlan.config,
        buyPoints: stockPlan.buyPoints.map(point => ({
          order: point.order,
          // targetPrice: point.targetPrice.toString(),
          targetPrice: point.targetPrice,
          // buyAmount: point.actualAmount.toString(),
          buyAmount: point.actualAmount,
          // shares: point.shares.toString(),
          shares: point.shares,
          priceDropPercent: point.priceDropPercent,
          triggerCondition: point.triggerCondition
        })),
        totalInvestment: stockPlan.totalInvestment,
        expectedShares: stockPlan.totalShares,
        averagePrice: stockPlan.averagePrice,
        riskAnalysis: stockPlan.riskAnalysis,
        stockInfo: stockInfoFromPlan
      };
      setInvestmentPlan(plan);
    }
  }, [initialPlan, form]);

  // 计算投资计划
  const handleGeneratePlan = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      const newStockInfo: StockInfo = {
        code: values.code,
        name: values.name,
        currentPrice: values.currentPrice,
        maxDrawdown: values.maxDrawdown,
        currency: 'CNY',
        type: 'STOCK'
      };
      
      const newConfig: InvestmentConfig = {
        totalAmount: values.totalAmount,
        buyTimes: values.buyTimes,
        strategy: values.strategy,
        riskLevel: 3
      };
      
      setStockInfo(newStockInfo);
      setConfig(newConfig);
      
      const stockPlan = StockInvestmentCalculator.generateStockInvestmentPlan(newStockInfo, newConfig);
      const plan: InvestmentPlan = {
        config: stockPlan.config,
        buyPoints: stockPlan.buyPoints.map(point => ({
          order: point.order,
          // targetPrice: point.targetPrice.toString(),
          targetPrice: point.targetPrice,
          // buyAmount: point.actualAmount.toString(),
          buyAmount: point.actualAmount,
          // shares: point.shares.toString(),
          shares: point.shares,
          priceDropPercent: point.priceDropPercent,
          triggerCondition: point.triggerCondition
        })),
        totalInvestment: stockPlan.totalInvestment,
        expectedShares: stockPlan.totalShares,
        averagePrice: stockPlan.averagePrice,
        riskAnalysis: stockPlan.riskAnalysis,
        stockInfo: newStockInfo
      };
      setInvestmentPlan(plan);
      
      message.success('投资计划生成成功！');
    } catch (error) {
      message.error('请填写完整的证券信息');
    } finally {
      setLoading(false);
    }
  };

  // 保存投资计划
  const handleSave = () => {
    if (!investmentPlan) {
      message.error('请先生成投资计划');
      return;
    }
    
    onSave?.(investmentPlan);
  };

  // 效率指标
  const efficiencyMetrics: EfficiencyMetrics | null = useMemo(() => {
    if (investmentPlan) {
      // 重新构建StockInvestmentPlan 对象用于效率计算
      const stockPlan = {
        stockInfo: investmentPlan.stockInfo,
        config: investmentPlan.config,
        buyPoints: investmentPlan.buyPoints.map(point => ({
          order: point.order,
          targetPrice: parseFloat(point.targetPrice.toFixed(3)),
          buyAmount: parseFloat(point.buyAmount.toFixed(2)),
          targetAmount: parseFloat(point.buyAmount.toFixed(2)),
          actualAmount: parseFloat(point.buyAmount.toFixed(2)),
          shares: parseInt(point.shares.toFixed(2)),
          amountDifference: 0,
          priceDropPercent: point.priceDropPercent,
          triggerCondition: point.triggerCondition
        })),
        totalInvestment: investmentPlan.totalInvestment,
        totalShares: investmentPlan.expectedShares,
        averagePrice: investmentPlan.averagePrice,
        targetAmount: investmentPlan.config.totalAmount,
        amountDifference: investmentPlan.totalInvestment - investmentPlan.config.totalAmount,
        riskAnalysis: investmentPlan.riskAnalysis
      };
      return StockInvestmentCalculator.calculateEfficiencyMetrics(stockPlan);
    }
    return null;
  }, [investmentPlan]);

  // 导出计划
  const handleExportPlan = () => {
    if (!investmentPlan) return;
    
    const planText = generatePlanText(investmentPlan);
    const blob = new Blob([planText], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${stockInfo.code}_投资计划.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    message.success('投资计划已导出');
  };

  const generatePlanText = (plan: InvestmentPlan): string => {
    const { stockInfo, buyPoints, riskAnalysis } = plan;
    let text = `证券投资计划\n`;
    text += `================\n\n`;
    text += `证券信息：\n`;
    text += `代码：${stockInfo.code}\n`;
    text += `名称：${stockInfo.name}\n`;
    text += `当前价格：${stockInfo.currentPrice} ${stockInfo.currency}\n`;
    text += `历史最大回撤：${stockInfo.maxDrawdown}%\n\n`;
    
    text += `投资配置：\n`;
    text += `总投资金额：${config.totalAmount} ${stockInfo.currency}\n`;
    text += `计划买入次数：${config.buyTimes} 次\n`;
    text += `投资策略：${StockInvestmentCalculator.getStrategyDescription(config.strategy as StrategyType)}\n\n`;
    
    text += `买入计划：\n`;
    text += `序号\t目标价格\t买入金额\t买入份额\t跌幅\t触发条件\n`;
    buyPoints.forEach(point => {
      text += `${point.order}\t${point.targetPrice}\t${point.buyAmount}\t${point.shares}\t${point.priceDropPercent}%\t${point.triggerCondition}\n`;
    });
    
    text += `\n风险分析：\n`;
    text += `预期平均成本：${plan.averagePrice.toFixed(3)} ${stockInfo.currency}\n`;
    text += `最大可能亏损：${riskAnalysis.maxLoss}%\n`;
    text += `盈亏平衡价格：${riskAnalysis.breakEvenPrice} ${stockInfo.currency}\n`;
    text += `风险等级：${riskAnalysis.riskLevel}\n`;
    
    return text;
  };

  // 买入计划表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'order',
      width: 80,
      align: 'center' as const
    },
    {
      title: '目标价格',
      dataIndex: 'targetPrice',
      key: 'targetPrice',
      render: (price: string) => `¥${price}`
    },
    {
      title: '买入金额',
      dataIndex: 'buyAmount',
      key: 'buyAmount',
      render: (amount: string) => `¥${amount}`
    },
    {
      title: '买入份额',
      dataIndex: 'shares',
      key: 'shares',
      render: (shares: string) => `${shares} 份`
    },
    {
      title: '跌幅',
      dataIndex: 'priceDropPercent',
      key: 'priceDropPercent',
      render: (percent: number) => (
        <Tag color={percent === 0 ? 'blue' : percent > 0 ? 'green' : 'red'}>
          {percent > 0 ? `-${percent}` : percent}%
        </Tag>
      )
    },
    {
      title: '触发条件',
      dataIndex: 'triggerCondition',
      key: 'triggerCondition',
      ellipsis: true
    }
  ];

  const getRiskColor = (riskLevel: string): string => {
    const colors: Record<string, string> = {
      '低风险': '#3f8600',
      '中等风险': '#cf1322',
      '较高风险': '#cf1322',
      '高风险': '#cf1322'
    };
    return colors[riskLevel] || '#000';
  };

  const getPageTitle = () => {
    switch (mode) {
      case 'create':
        return '新增证券投资计划';
      case 'edit':
        return '编辑证券投资计划';
      case 'view':
        return '证券投资计划详情';
      default:
        return '证券投资计划';
    }
  };

  return (
    <div className="stock-investment-plan-form">
      <div style={{ marginBottom: 24 }}>
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={onBack}>
            返回列表
          </Button>
          <Title level={2} style={{ margin: 0 }}>
            <CalculatorOutlined /> {getPageTitle()}
          </Title>
        </Space>
      </div>

      <Row gutter={[24, 24]}>
        {/* 配置表单 */}
        <Col xs={24} lg={8}>
          <Card title="投资配置" size="small">
            <Form
              form={form}
              layout="vertical"
              initialValues={{
                code: '',
                name: '',
                currentPrice: undefined,
                maxDrawdown: -30,
                totalAmount: 10000,
                buyTimes: 5,
                strategy: 'pyramid'
              }}
            >
              <Form.Item
                label="证券代码"
                name="code"
                rules={[{ required: true, message: '请输入证券代码' }]}
              >
                <Input placeholder="如：510300" disabled={isReadOnly} />
              </Form.Item>

              <Form.Item
                label="证券名称"
                name="name"
                rules={[{ required: true, message: '请输入证券名称' }]}
              >
                <Input placeholder="如：沪深300ETF" disabled={isReadOnly} />
              </Form.Item>

              <Form.Item
                label="当前价格"
                name="currentPrice"
                rules={[{ required: true, message: '请输入当前价格' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="当前市场价格"
                  min={0}
                  step={0.01}
                  precision={2}
                  disabled={isReadOnly}
                />
              </Form.Item>

              <Form.Item
                label="历史最大回撤 (%)"
                name="maxDrawdown"
                tooltip="历史上该资产的最大跌幅，用于计算买入区间"
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="-30"
                  max={0}
                  step={1}
                  disabled={isReadOnly}
                />
              </Form.Item>

              <Form.Item
                label="总投资金额"
                name="totalAmount"
                rules={[{ required: true, message: '请输入总投资金额' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="10000"
                  min={1}
                  step={1000}
                  disabled={isReadOnly}
                />
              </Form.Item>

              <Form.Item
                label="计划买入次数"
                name="buyTimes"
                rules={[{ required: true, message: '请选择买入次数' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  min={2}
                  max={10}
                  step={1}
                  disabled={isReadOnly}
                />
              </Form.Item>

              <Form.Item
                label="投资策略"
                name="strategy"
                tooltip="不同策略的资金分配方式不同"
              >
                <Select placeholder="选择投资策略" disabled={isReadOnly}>
                  <Option value="equal">等额投资</Option>
                  <Option value="pyramid">金字塔策略</Option>
                  <Option value="aggressive">激进策略</Option>
                </Select>
              </Form.Item>

              {!isReadOnly && (
                <Button 
                  type="primary" 
                  block 
                  icon={<CalculatorOutlined />}
                  loading={loading}
                  onClick={handleGeneratePlan}
                >
                  生成投资计划
                </Button>
              )}
            </Form>
          </Card>

          {/* 策略说明 */}
          <Card title="策略说明" size="small" style={{ marginTop: 16 }}>
            <Space direction="vertical" size="small">
              <div>
                <Text strong>等额投资：</Text>
                <br />
                <Text type="secondary">每次买入相同金额，风险分散均匀</Text>
              </div>
              <div>
                <Text strong>金字塔策略：</Text>
                <br />
                <Text type="secondary">价格越低买入越多，适合长期投资</Text>
              </div>
              <div>
                <Text strong>激进策略：</Text>
                <br />
                <Text type="secondary">大幅下跌时重仓买入，高风险高收益</Text>
              </div>
            </Space>
          </Card>
        </Col>

        {/* 投资计划结果 */}
        <Col xs={24} lg={16}>
          {investmentPlan ? (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              {/* 概览统计 */}
              <Row gutter={16}>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="总投资金额"
                      value={investmentPlan.totalInvestment}
                      precision={2}
                      prefix="¥"
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="预期份额"
                      value={investmentPlan.expectedShares}
                      precision={0}
                      suffix="份"
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="平均成本"
                      value={investmentPlan.averagePrice}
                      precision={2}
                      prefix="¥"
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="风险等级"
                      value={investmentPlan.riskAnalysis.riskLevel}
                      valueStyle={{ 
                        color: getRiskColor(investmentPlan.riskAnalysis.riskLevel)
                      }}
                    />
                  </Card>
                </Col>
              </Row>

              {/* 风险分析 */}
              <Card 
                title="风险分析" 
                size="small"
                extra={
                  <Space>
                    {!isReadOnly && onSave && (
                      <Button 
                        type="primary" 
                        icon={<SaveOutlined />}
                        onClick={handleSave}
                      >
                        保存计划
                      </Button>
                    )}
                    <Button 
                      icon={<DownloadOutlined />}
                      onClick={handleExportPlan}
                    >
                      导出计划
                    </Button>
                  </Space>
                }
              >
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="最大可能亏损"
                      value={investmentPlan.riskAnalysis.maxLoss}
                      precision={2}
                      suffix="%"
                      valueStyle={{ color: '#cf1322' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="盈亏平衡价格"
                      value={investmentPlan.riskAnalysis.breakEvenPrice}
                      precision={2}
                      prefix="¥"
                    />
                  </Col>
                  {efficiencyMetrics && (
                    <Col span={8}>
                      <Statistic
                        title="成本优势"
                        value={efficiencyMetrics.costAdvantage}
                        precision={2}
                        suffix="%"
                        valueStyle={{ color: '#3f8600' }}
                        prefix="+"
                      />
                    </Col>
                  )}
                </Row>
              </Card>

              {/* 买入计划表格 */}
              <Card title="分批买入计划" size="small">
                <Table
                  columns={columns}
                  dataSource={investmentPlan.buyPoints}
                  rowKey="order"
                  pagination={false}
                  size="small"
                />
              </Card>

              {/* 投资建议 */}
              <Alert
                message="投资建议"
                description={
                  <ul style={{ margin: 0, paddingLeft: 20 }}>
                    <li>建议设置价格提醒，当证券价格达到目标买入点时及时执行</li>
                    <li>分批投资需要耐心，不要因为短期波动而改变计划</li>
                    <li>定期回顾和调整计划，特别是当基本面发生重大变化时</li>
                    <li>保持足够的现金流，确保能够按计划执行所有买入点</li>
                    <li>考虑设置止损点，当亏损超过预期时及时调整策略</li>
                  </ul>
                }
                type="info"
                icon={<InfoCircleOutlined />}
                showIcon
              />
            </Space>
          ) : (
            <Card>
              <div style={{ textAlign: 'center', padding: '60px 0' }}>
                <TrophyOutlined style={{ fontSize: 64, color: '#d9d9d9' }} />
                <Title level={4} type="secondary">
                  请填证券信息并生成投资计划
                </Title>
                <Paragraph type="secondary">
                  基于历史回撤数据，为您制定科学的分批投资策略
                </Paragraph>
              </div>
            </Card>
          )}
        </Col>
      </Row>
    </div>
  );
};

export default StockInvestmentPlanForm;